import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";

import React from "react";

import { addon, log, getObject, Ref } from "pao-aop";
import { SingleProductSignCondition, ICompanyTemplateSignService } from "src/models/companySign";
import { ExternalLinksSign } from "src/models/externalLinksSign";
import SignFrameLayout, { InputType } from "src/business/style-components/sign-frame-layout";
import { SingleProductSign } from "src/models/singleProductSign";
import { NTOperationTable } from "src/business/components/operation-table";
import { SignDetailLayout } from "src/projects/industryInternetSign/layout/sgin-detail-layout";
import { change_structure, ROUTE_PATH, isPermission, COMPANY_ID } from "../../app/util-tool";
import { IProductTypeService } from "src/models/productType";
import { ColumnConfig } from "src/business/components/detail";
import { message } from "antd";
import { PermissionList } from "../../app/permission";
/**
 * 组件：企业模板标识详情视图控件状态
 */
export interface CompanyTemplateDetailState extends ReactViewState {
    /** 数据源 */
    data?: any;
    /** 单品标识列表数据源 */
    single_data_source?: any[];
    /** 单品当前第几页 */
    single_page?: number;
    /** 单品当前每页数 */
    single_pageSize?: number;
    /** 单品数据总条数 */
    single_total_data?: number;
    /** 品类标识列表数据源 */
    category_data_source?: any[];
    /** 品类当前第几页 */
    category_page?: number;
    /** 品类当前每页数 */
    category_pageSize?: number;
    /** 品类数据总条数 */
    category_total_data?: number;
    /** 跳转标识列表数据源 */
    external_data_source?: any[];
    /** 跳转当前第几页 */
    external_page?: number;
    /** 跳转当前每页数 */
    external_pageSize?: number;
    /** 跳转数据总条数 */
    external_total_data?: number;
    /** 单品查询条件对象单品 */
    condition_single?: SingleProductSignCondition;
    /** 品类查询条件对象品类 */
    condition_category?: SingleProductSignCondition;
    /** 跳转查询条件对象跳转 */
    condition_external?: ExternalLinksSign;
    /** 产品类型列表 */
    product_data?: any;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：企业模板标识详情视图控件
 * 描述
 */
export class CompanyTemplateDetail extends ReactView<CompanyTemplateDetailControl, CompanyTemplateDetailState> {
    // table 品类名字
    category_columns_data_source = [{
        title: '单品名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500,
    }, {
        title: '产品类型',
        dataIndex: 'product_type',
        key: 'product_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let product = this.state.product_data;
            if (text && product) {
                return product.get(text) ? product.get(text) : text;
            }
        }
    }, {
        title: '单品标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    // table 单品
    single_columns_data_source = [{
        title: '单品名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500,
    }, {
        title: '产品类型',
        dataIndex: 'product_type',
        key: 'product_type',
        width: 150,
        render: (text: string, record: any, index: any) => {
            let product = this.state.product_data;
            if (text && product) {
                return product.get(text) ? product.get(text) : text;
            }
        }
    }, {
        title: '单品标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
    }, {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    // table 跳转
    externalLinks_columns_data_source = [{
        title: '单品名称',
        dataIndex: 'handle_name',
        key: 'handle_name',
        width: 500,
    },
    {
        title: '单品标识',
        dataIndex: 'handle_code',
        key: 'handle_code',
        width: 500,
    },
    {
        title: '创建时间',
        dataIndex: 'create_date',
        key: 'create_date',
        width: 150,
    }];
    constructor(props: CompanyTemplateDetailControl) {
        super(props);
        this.state = {
            single_page: 1,
            single_pageSize: 10,
            category_page: 1,
            category_pageSize: 10,
            external_page: 1,
            external_pageSize: 10,
            loading: false
        };
    }
    /** 分页回调事件 */
    single_pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            single_page: contents,
            loading: true
        });
        this.single_queryList(this.state.condition_single ? this.state.condition_single! : {}, contents, this.state.single_pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    single_showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            single_pageSize: pageSize,
            loading: true
        });
        this.single_queryList(this.state.condition_single ? this.state.condition_single! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 修改Icon回调事件 */
    onClickEditor = () => {
        this.props.history!.push(ROUTE_PATH.changeCompanyTemplateView + `/${this.state.data!.id}`);
    }
    /** 删除Icon回调事件 */
    onClickDel = () => {
        this.setState({
            loading: true
        });
        this.deleteDeatail()
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("ProductDetailViewControl-delete", error.message);
            });
    }
    // 查询回调
    private search_single = (e: any, val: any) => {
        let { [COMPANY_ID]: id } = this.props.match!.params;
        val.id = id;
        this.setState({
            condition_single: val,
            loading: true
        });
        this.single_queryList(val, 1, this.state.single_pageSize ? this.state.single_pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("SingleProductDetailViewControl", error.message);
            });
    }
    // 重置回调
    private reset_single = () => {
        console.log("重置回调");
        this.setState({
            condition_single: {}
        });
    }

    // 品类
    /** 分页回调事件 */
    category_pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            category_page: contents,
            loading: true
        });
        this.category_queryList(this.state.condition_category ? this.state.condition_category! : {}, contents, this.state.category_pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("category_StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    category_showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            category_pageSize: pageSize,
            loading: true
        });
        this.category_queryList(this.state.condition_category ? this.state.condition_category! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("category_StatisticalAnalysisViewControl", error.message);
            });
    }
    // 查询回调
    private search_category = (e: any, val: any) => {
        let { [COMPANY_ID]: id } = this.props.match!.params;
        val.id = id;
        this.setState({
            condition_single: val,
            loading: true
        });
        this.category_queryList(val, 1, this.state.category_pageSize ? this.state.category_pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("category_ProductDetailViewControl", error.message);
            });
    }
    // 重置回调
    private reset_category = () => {
        console.log("重置回调");
        this.setState({
            condition_category: {}
        });
    }

    // 跳转
    /** 分页回调事件 */
    external_pageOnCick = (contents: any) => {
        console.log('page:', contents);
        this.setState({
            external_page: contents,
            loading: true
        });
        this.external_queryList(this.state.condition_external ? this.state.condition_external! : {}, contents, this.state.external_pageSize!)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    /** 改变分页数量回调事件 */
    external_showSizeChange = (current: number, pageSize: number) => {
        console.log('current: ' + current + 'pageSize: ' + pageSize);
        this.setState({
            external_pageSize: pageSize,
            loading: true
        });
        this.external_queryList(this.state.condition_external ? this.state.condition_external! : {}, 1, pageSize)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("StatisticalAnalysisViewControl", error.message);
            });
    }
    // 查询回调
    private search_external = (e: any, val: any) => {
        let { [COMPANY_ID]: id } = this.props.match!.params;
        val.id = id;
        this.setState({
            condition_external: val,
            loading: true
        });
        this.external_queryList(val, 1, this.state.external_pageSize ? this.state.external_pageSize : 10)
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("SingleProductDetailViewControl", error.message);
            });
    }
    // 重置回调
    private reset_external = () => {
        console.log("重置回调");
        this.setState({
            condition_external: {}
        });
    }
    componentWillMount() {
        // 初始化数据源
        this.setState({
            data: new SingleProductSign(),

        });
    }
    componentDidMount() {
        this.setState({
            loading: true
        });
        this.queryData()
            .then(() => {
                this.setState({
                    loading: false
                });
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                log("???", error.message);
            });
    }
    // 初始化服务
    companyTemplateProductSignService?() {
        return getObject(this.props.companyTemplateSignService_fac!);
    }
    // 初始化产品类型服务
    productTypeService?() {
        return getObject(this.props.productTypeService_Fac!);
    }
    // 删除单品详情信息
    async deleteDeatail() {
        const result = await this.companyTemplateProductSignService!()!.delete_company!([this.props.match!.params.key])!;
        message.info("删除" + (result ? '成功' : '失败'));
        if (result) {
            this.props.history!.push(ROUTE_PATH.companyTemplateView);
        }
    }
    // 查询单品表格列表信息
    async single_queryList(condition: Object, page: number, count: number) {
        const data_list = await this.companyTemplateProductSignService!()!.get_single_list!(condition, page, count)!;
        this.setState({
            single_data_source: data_list ? data_list!['result'] : []
        });
    }
    // 查询品类表格列表信息
    async category_queryList(condition: Object, page: number, count: number) {
        const data_list = await this.companyTemplateProductSignService!()!.get_category_list!(condition, page, count)!;
        this.setState({
            category_data_source: data_list ? data_list!['result'] : []
        });
    }
    // 查询跳转表格列表信息
    async external_queryList(condition: Object, page: number, count: number) {
        const data_list = await this.companyTemplateProductSignService!()!.get_externam_link_list!(condition, page, count)!;
        this.setState({
            single_data_source: data_list ? data_list!['result'] : []
        });
    }
    // 查询详情信息
    async queryData() {
        let { [COMPANY_ID]: id } = this.props.match!.params;
        const data = await this.companyTemplateProductSignService!()!.get_company_sign!(id)!;
        if (data) {
            data!.address = data!.address!.province + data!.address!.city + data!.address!.area + data!.address!.detail;
            let email = '';
            for (let i = 0; i < data!.email!.length; i++) {
                email = email + data!.email![i].title + ',';
            }
            data!.email = email.slice(0, email.length - 1);

            let fax = '';
            for (let i = 0; i < data!.fax!.length; i++) {
                fax = fax + data!.fax![i].title + ':' + data!.fax![i].contents + ',';
            }
            data!.fax = fax.slice(0, fax.length - 1);

            let mobile = '';
            for (let i = 0; i < data!.mobile!.length; i++) {
                mobile = mobile + data!.mobile![i].title + ':' + data!.mobile![i].contents + ',';
            }
            data!.mobile = mobile.slice(0, mobile.length - 1);

            let tel = '';
            for (let i = 0; i < data!.tel!.length; i++) {
                tel = tel + data!.tel![i].title + ':' + data!.tel![i].contents + ',';
            }
            data!.tel = tel.slice(0, tel.length - 1);
        }
        let condition: SingleProductSignCondition = {};
        condition.id = data ? data!.id : '';
        const single_data_list = await this.companyTemplateProductSignService!()!.get_single_list!(condition, this.state.single_page ? this.state.single_page : 1, this.state.single_pageSize ? this.state.single_pageSize : 10)!;
        const category_data_list = await this.companyTemplateProductSignService!()!.get_category_list!(condition, this.state.category_page ? this.state.category_page : 1, this.state.category_pageSize ? this.state.category_pageSize : 10)!;
        const external_data_list = await this.companyTemplateProductSignService!()!.get_externam_link_list!(condition, this.state.external_page ? this.state.external_page : 1, this.state.external_pageSize ? this.state.external_pageSize : 10)!;
        const product_data = await this.productTypeService!()!.get_product_type_list!()!;
        let product_map = change_structure('product_type_name', product_data!.result);
        this.setState({
            data: data,
            single_total_data: single_data_list ? single_data_list!.total : 0,
            single_data_source: single_data_list ? single_data_list!.result : [],
            category_total_data: category_data_list ? category_data_list!.total : 0,
            category_data_source: category_data_list ? category_data_list!.result : [],
            external_total_data: external_data_list ? external_data_list!.total : 0,
            external_data_source: external_data_list ? external_data_list!.result : [],
            product_data: product_map
        });
    }

    render() {
        let { [COMPANY_ID]: id } = this.props.match!.params;
        const redeirect = isPermission ? isPermission!(PermissionList.CompanyTemplate_Select, id) : undefined;
        if (redeirect) {
            return redeirect;
        }
        let { data } = this.state;
        // 详情匹配数组
        let category_title_detail_columns: ColumnConfig[] = [
            { title: '企业模板标识:', fieldName: 'handle_code' },
            { title: '组织机构代码:', fieldName: 'organization' },
            { title: '手机号码:', fieldName: 'mobile' },
            { title: '固定电话:', fieldName: 'tel' },
            { title: '电子邮箱:', fieldName: 'email' },
            { title: '公司地址:', fieldName: 'address' },
            { title: '企业官网:', fieldName: 'website' },
            { title: '企业介绍:', fieldName: 'introduce' },
            { title: '创建日期:', fieldName: 'create_date' },
        ];
        if (data && data.custom_attribute) {
            for (let i = 0; i < data.custom_attribute.length; i++) {
                category_title_detail_columns.push({
                    title: data.custom_attribute[i].label! + ': ', // + (data.custom_attribute[i].value instanceof Array ? '' : data.custom_attribute[i].value!),
                    fieldName: 'custom_attribute' + i, // data.custom_attribute[i].value!,
                    type: data.custom_attribute[i].value instanceof Array ? 'img' : undefined
                });
                data['custom_attribute' + i] = data.custom_attribute[i].value!;
            }
        }
        let category_model_props = {
            edit_form_items_props: [{
                type: InputType.input,
                label: "品类模板名称",
                decorator_id: "handle_name",
                default_value: "",
                option: {
                    placeholder: "请输入品类模板名称"
                }
            },
            {
                type: InputType.input,
                label: "品类模板标识",
                decorator_id: "handle_code",
                default_value: "",
                option: {
                    placeholder: "请输入品类模板标识"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date"
            }],
            showTable: (
                <NTOperationTable
                    data_source={this.state.category_data_source}
                    columns_data_source={this.category_columns_data_source}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.category_total_data}
                    default_page_size={10}
                    show_footer={true}
                    total_pages={Math.ceil((this.state.category_total_data ? this.state.category_total_data : 0) / 10)}
                    page_on_click={this.category_pageOnCick}
                    rowKey='id'
                    show_size_change={this.category_showSizeChange}
                />),
            search_cb: this.search_category,
            reset_cb: this.reset_category
        };
        let single_model_props = {
            edit_form_items_props: [{
                type: InputType.input,
                label: "单品名称",
                decorator_id: "handle_name",
                default_value: "",
                option: {
                    placeholder: "请输入单品名称"
                }
            },
            {
                type: InputType.input,
                label: "标识码",
                decorator_id: "handle_code",
                default_value: "",
                option: {
                    placeholder: "请输入标识码"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date"
            }],
            showTable: (
                <NTOperationTable
                    data_source={this.state.single_data_source}
                    columns_data_source={this.single_columns_data_source}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.single_total_data}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.single_total_data ? this.state.single_total_data : 0) / 10)}
                    show_footer={true}
                    page_on_click={this.single_pageOnCick}
                    rowKey='id'
                    show_size_change={this.single_showSizeChange}
                />),
            search_cb: this.search_single,
            reset_cb: this.reset_single
        };
        let external_model_props = {
            edit_form_items_props: [{
                type: InputType.input,
                label: "跳转标识名称",
                decorator_id: "handle_name",
                default_value: "",
                option: {
                    placeholder: "请输入跳转标识名称"
                }
            },
            {
                type: InputType.input,
                label: "跳转标识",
                decorator_id: "handle_code",
                default_value: "",
                option: {
                    placeholder: "请输入跳转标识"
                }
            },
            {
                type: InputType.date,
                label: "创建时间",
                decorator_id: "create_date"
            }],
            showTable: (
                <NTOperationTable
                    data_source={this.state.external_data_source}
                    columns_data_source={this.externalLinks_columns_data_source}
                    table_size='middle'
                    showHeader={true}
                    bordered={false}
                    total={this.state.single_total_data ? this.state.single_total_data : 0}
                    default_page_size={10}
                    total_pages={Math.ceil((this.state.single_total_data ? this.state.single_total_data : 1) / 10)}
                    show_footer={true}
                    page_on_click={this.external_pageOnCick}
                    show_size_change={this.external_showSizeChange}
                    rowKey='id'
                />),
            search_cb: this.search_external,
            reset_cb: this.reset_external
        };
        let this_props = {
            loading: this.state.loading,
            title_name: this.state.data!.handle_name,
            rc_code: this.state.data!.rc_code,
            title_detail_columns: category_title_detail_columns,
            title_detail_columns_data: data,
            icon_props: [{
                icon: 'antd@edit',
                btn_method: this.onClickEditor
            }],
            picture: { title_name: '企业照片', picture_data: this.state.data!.company_picture },
            tab: [{
                name: '品类模板标识',
                showElement: (
                    <SignFrameLayout {...category_model_props} />
                )
            }, {
                name: '单品标识',
                showElement: (
                    <SignFrameLayout {...single_model_props} />
                )
            }, {
                name: '跳转标识',
                showElement: (
                    <SignFrameLayout {...external_model_props} />
                )
            }]
        };
        return (
            <SignDetailLayout {...this_props} />
        );
    }
}

/**
 * 控件：企业模板标识详情视图控件控制器
 * 描述
 */
@addon('CompanyTemplateDetail', '企业模板标识详情视图控件', '企业模板标识详情视图控件')
@reactControl(CompanyTemplateDetail, true)
export class CompanyTemplateDetailControl extends ReactViewControl {
    /**
     * 企业标识服务
     */
    public companyTemplateSignService_fac?: Ref<ICompanyTemplateSignService>;
    /** 
     * 产品类型服务
     */
    public productTypeService_Fac?: Ref<IProductTypeService>;
    constructor() {
        super();
    }
}